package com.hean.activity;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.hean.entity.Cell;
import com.hean.entity.Worm;
import com.hean.view.WormView;

public class WormGame extends Activity {
	public static final int MSG_INVALIDATE = 1;
	private WormView gameView;
	private Worm worm;
	private WormStepThread wormStepThread;
	/**
	 * 
	 */
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == MSG_INVALIDATE) {
				gameView.invalidate();
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		worm = new Worm(8, new Cell(0, 0), 25, 30);

		setContentView(R.layout.wormgame);
		gameView = (WormView) findViewById(R.id.wormgame_view);
		gameView.setWorm(worm);

		Button start = (Button) findViewById(R.id.wormgame_start);
		Button stop = (Button) findViewById(R.id.wormgame_stop);

		start.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (wormStepThread == null) {
					wormStepThread = new WormStepThread();
					wormStepThread.setRun(true);
					wormStepThread.start();
				}
			}
		});

		stop.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (wormStepThread != null) {
					wormStepThread.setRun(false);
					wormStepThread.interrupt();//使线程抛InterruptedException异常，不在sleep结束时，再走一步
					wormStepThread = null;
				}
			}
		});

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		boolean ok = false;
		if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
			ok = worm.changeDirection(Worm.D_LEFT);
		} else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
			ok = worm.changeDirection(Worm.D_RIGHT);
		} else if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
			ok = worm.changeDirection(Worm.D_UP);
		} else if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
			ok = worm.changeDirection(Worm.D_DOWN);
		}
		if (ok) {
			//改变方向后多加速一步
			worm.step();
			//是否到了边界
			gameView.invalidate();
		}
		return super.onKeyDown(keyCode, event);
	}

	private class WormStepThread extends Thread {
		private boolean run = false;

		@Override
		public void run() {
			try {
				while (run) {
					Thread.sleep(200);
					worm.step();
					Message msg = new Message();
					msg.what = MSG_INVALIDATE;
					handler.sendMessage(msg);
				}
			} catch (InterruptedException e) {
			}
		}

		public synchronized void setRun(boolean run) {
			this.run = run;
		}
	}
}
